import string from "./string";

/**
 *
 * 本地存储
 */
var storage = {
  //--------------localStorage----------------------------
  setData: function (name, obj) {
    if (typeof obj === "object") {
      obj = JSON.stringify(obj);  //将obj转为String类型

      //var obj = "{userName:userName,password:password}"
    }
    localStorage.setItem(name, obj);  //localStorage存储
  },
  getData: function (key) {
    var data;
    try {
      var obj = localStorage.getItem(key);
      data = JSON.parse(obj);  //将obj转为JSON  localStorage只能存取字符串。所以取出的必须转换成对象
    } catch (e) {
      data = obj;
    }
    return data;
  },
  //清除指定的存储
  rmStorage: function (key) {
    localStorage.removeItem(key);
    //localStorage.clear();  清空所有
  },


  //--------------sessionStorage----------------------------

  setSessionData: function (name, obj) {
    if (typeof obj === "object") {
      obj = JSON.stringify(obj);  //将obj转为String类型

    }
    sessionStorage.setItem(name, obj);  //localStorage存储
  },
  getSessionData: function (key) {
    var data;
    try {
      var obj = sessionStorage.getItem(key);
      data = JSON.parse(obj);  //将obj转为JSON
    } catch (e) {
      data = obj;
    }
    return data;
  },
  //清除指定的存储
  rmSessionStorage: function (key) {
    sessionStorage.removeItem(key);
  },
  /**
   *@author    zxd
   * @param name cookie名
   * @param value  存储值
   * @param days  有效期（天）
   */
  setCookie : function (name, value, days) {
    var d = new Date();
    d.setTime(d.getTime() + 24*60*60*1000*days);
    window.document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
  },

  /**
   *@author    zxd
   * @param name cookie名
   * @returns {null}
   */
  getCookie : function (name) {
    var v = window.document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return v ? v[2] : null;
  },

  /**
   * @author    zxd
   * 根据cookie名删除
   * @param name
   */
  deleteCookie : function (name) {
    this.setCookie(name, '', -1);
  }
}

export default  storage;
